﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;

namespace CRM.Web.Admin
{
    public partial class ValidateCode : System.Web.UI.Page
    {
        private const double imageLengthBase = 12.5;
        private const int imageHeigth = 22;//验证码图片的高度
        private const int imageLineNumber = 25;//图片干扰线的数目
        private const int imagePointNumber = 100;
        public static string validateCodeKey = "validateCodeKey";
        private int length = 4;//获取和设置验证码的长度，即验证码的字符的数量
        private string code = string.Empty;//获取验证码

        /// <summary>
        /// 获取或设置验证码的长度，默认值为4
        /// </summary>
        public int Length
        {
            get { return length; }
            set { length = value; }
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        public string Code
        {
            get { return code; }
            set { code = value; }
        }

        public ValidateCode()
        {

        }

        /// <summary>
        /// 创建随机验证码
        /// </summary>
        /// <param name="length">验证码长度</param>
        /// <returns>返回验证码code</returns>
        public string createCode(int length)
        {
            if (length <= 0) return string.Empty;
            //创建一组随机数,用来创建验证码
            Random random = new Random();
            StringBuilder newCode = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                newCode.Append(random.Next(0, 10));
            }
            //保存验证码到Session对象中
            code = newCode.ToString();
            Session[validateCodeKey] = code;
            return code;
        }

        /// <summary>
        /// 创建验证码的图片和验证码
        /// </summary>
        /// <param name="code">验证码</param>
        public void createValidateImage(string code)
        {
            if (string.IsNullOrEmpty(code) == true)
                return;
            //保存验证码到Session对象中
            Session[validateCodeKey] = code;
            //创建一个图象
            Bitmap image = new Bitmap((int)Math.Ceiling((code.Length * imageLengthBase)), imageHeigth);
            Graphics graphic = Graphics.FromImage(image);

            Random random = new Random();
            try
            {
                graphic.Clear(Color.White);//清空图象，并指定填充颜色
                //绘制图片的干扰线
                int x1, x2, y1, y2;
                for (int i = 0; i < imageLineNumber; i++)
                {
                    x1 = random.Next(image.Width);
                    y1 = random.Next(image.Height);
                    x2 = random.Next(image.Width);
                    y2 = random.Next(image.Height);
                    //绘制干扰线
                    graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                    //绘制验证码
                    Font font = new Font("Tahoma", 12, FontStyle.Bold | FontStyle.Italic);
                    LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                    graphic.DrawString(code, font, brush, 2.0f, 2.0f);
                }
                //绘制图片的前景噪音点
                int x, y;
                for (int i = 0; i < imageLineNumber; i++)
                {
                    x = random.Next(image.Width);
                    y = random.Next(image.Height);
                    //绘制点
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                    //画图片的边框线
                    graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                    //保存图片的内容到流中
                    MemoryStream ms = new MemoryStream();
                    image.Save(ms, ImageFormat.Gif);
                    //输出图片
                    System.Web.HttpContext.Current.Response.ClearContent();
                    System.Web.HttpContext.Current.Response.ContentType = "image/Gif";
                    System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                    //直接用Response对象会导致引用页面出现“响应在此上下文中不可用”的错误

                }
            }

            finally
            {
                graphic.Dispose();
                image.Dispose();
            }
        }

        /// <summary>
        /// 重载System.Web.UI.Page类中的Onload(EventArgs e)事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            createValidateImage(length);
        }

        /// <summary>
        /// 公开的createValidateImage(int length)方法，可以根据指定长度创建验证码(利用方法的多态性，不同的参数)
        /// </summary>
        /// <param name="length"></param>
        public void createValidateImage(int length)
        {
            code = createCode(length);
            createValidateImage(code);
        }
    }
}